
import path from 'node:path'
import fs from 'fs-extra'
import { Transformer, UiFile, WxApp, WxFile } from ".";
import { LogType, config, log } from "../util";
import { uniq } from 'lodash-es';


export class Wx2Ui extends Transformer {
    private app: WxFile;
    private uiApp: UiFile;

    constructor(src: string, dest: string) {
        super(src, dest);
    }
    init() {
        let appSrc = path.join(this.src, 'app.wxa');
        if (!fs.existsSync(appSrc)) {
            log.error('未找到app.wxa文件');
            return false;
        }
        let appDest = path.join(this.dest, 'app' + config.ext.ui);
        let app = new WxApp(appSrc, appDest, true);
        log.msg(LogType.READ, 'app.wxa配置');
        if (!app.config || !app.config.pages || app.config.pages.length === 0) {
            log.error('app.wxa未配置pages');
            return false;
        }
        this.app = app;
        return true;
    }

    async transform() {
        if (this.initSuccess) {
            this.copyScaffold();
            this.writeApp();
            await this.writePages();
            this.done();
        }
    }

    copyScaffold() {
        if (fs.existsSync(this.dest)) {
            fs.emptyDirSync(this.dest);
            log.msg(LogType.DELETE, this.dest);
        }
        let srcPath = path.join(__dirname, `../../scaffold/project/touchui`);
        let destStaticPath = this.dest;
        fs.copySync(srcPath, destStaticPath);
        log.msg(LogType.WRITE, '基础工程结构');
    }

    writeApp() {
        this.app.writeFile('app' + config.ext.ui);
    }

    async writePages() {
        let pages = this.getPages();
        let pageSrc;
        let page;
        for (let i = 0; i < pages.length; i++) {
            pageSrc = path.join(this.src, pages[i] + config.ext.wxp);
            if (!fs.existsSync(pageSrc)) {
                log.error(`未找到页面文件${pageSrc}`);
                continue;
            }
            let pageDest = path.join(this.dest, pages[i] + config.ext.ui);
            page = new WxFile(pageSrc, pageDest);
            await page.writeFile(pages[i] + config.ext.ui);
        }
    }

    getPages() {
        let { config } = this.app;
        let pages = config.pages;
        let tabs = [];
        if (config.tabBar && config.tabBar.list) {
            tabs = config.tabBar.list.map((item: any) => item.pagePath);
        }
        return uniq([...pages, ...tabs]);
    }

    done() {
        log.msg(LogType.COMPLETE, '小程序工程已转换为 TouchUI 工程');
    }
}
